package com.web.logindemo.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;


/**
 * 线程池相关类
 */
public class Threads {
    private static final Logger logger = LoggerFactory.getLogger(Threads.class);

    public static void sleep(long milliseconds){
        try{
            Thread.sleep(milliseconds);
        }
        catch (InterruptedException e){
            return;
        }
    }

    public static void shutdownAndAwaitTermination(ExecutorService pool){
        if(pool !=null && !pool.isShutdown()){
            pool.shutdown();
            try{
                if(!pool.awaitTermination(120, TimeUnit.SECONDS)){
                    pool.shutdown();
                    if(!pool.awaitTermination(120, TimeUnit.SECONDS)){
                        logger.info("Pool dod not terminate");
                    }
                }
            }catch (InterruptedException ie){
                pool.shutdown();
                Thread.currentThread().interrupt();
            }
        }
    }

    public static void printException(Runnable r, Throwable t){
        if(t==null&& r instanceof Future<?>){
            try{
                Future<?> future = (Future<?>) r;
                if(future.isDone()){
                    future.get();
                }
            }catch (CancellationException ce){
                t = ce;
            }catch (ExecutionException ee){
                t = ee.getCause();
            }catch (InterruptedException ie){
                Thread.currentThread().interrupt();
            }
        }
        if(t!=null){
            logger.error(t.getMessage(), t);
        }
    }
}
